package com.ruoyi.pos.web.service.impl;

import com.ruoyi.common.enums.AuditStatusEnum;
import com.ruoyi.common.enums.GoodsStatusEnum;
import com.ruoyi.common.enums.YesOrNoEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.pos.api.vo.user.UserInfoVo;
import com.ruoyi.pos.web.domain.*;
import com.ruoyi.pos.web.mapper.*;
import com.ruoyi.pos.web.service.ITTerminalGoodsInfoService;
import com.ruoyi.pos.web.webDto.TTerminalInfoWebDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品基础Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-15
 */
@Service
public class TTerminalGoodsInfoServiceImpl implements ITTerminalGoodsInfoService {
    @Autowired
    private TTerminalGoodsInfoMapper tTerminalGoodsInfoMapper;
    @Autowired
    private TTerminalGoodsImgInfoMapper terminalGoodsImgInfoMapper;
    @Autowired
    private TTerminalBrandInfoMapper tTerminalBrandInfoMapper;
    @Autowired
    private TTerminalInfoMapper terminalInfoMapper;
    @Autowired
    private TUserInfoMapper tUserInfoMapper;

    /**
     * 查询商品基础
     *
     * @param id 商品基础主键
     * @return 商品基础
     */
    @Override
    public TTerminalGoodsInfo selectTTerminalGoodsInfoById(String id) {
        TTerminalGoodsInfo terminalGoodsInfo = tTerminalGoodsInfoMapper.selectTTerminalGoodsInfoById(id);
        TTerminalGoodsImgInfo terminalGoodsImgInfo = new TTerminalGoodsImgInfo();
        terminalGoodsImgInfo.setGoodsId(id);
        List<TTerminalGoodsImgInfo> imgs = terminalGoodsImgInfoMapper.selectTTerminalGoodsImgInfoList(terminalGoodsImgInfo);
        String collect = imgs.stream().map(TTerminalGoodsImgInfo::getGoodsImg).collect(Collectors.joining(","));
        terminalGoodsInfo.setGoodsImgS(collect);
        System.out.println(collect);
        return terminalGoodsInfo;
    }

    /**
     * 查询商品基础列表
     *
     * @param tTerminalGoodsInfo 商品基础
     * @return 商品基础
     */
    @Override
    public List<TTerminalGoodsInfo> selectTTerminalGoodsInfoList(TTerminalGoodsInfo tTerminalGoodsInfo) {
        return tTerminalGoodsInfoMapper.selectTTerminalGoodsInfoList(tTerminalGoodsInfo);
    }

    /**
     * 新增商品基础
     *
     * @param tTerminalGoodsInfo 商品基础
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTTerminalGoodsInfo(TTerminalGoodsInfo tTerminalGoodsInfo) {
        tTerminalGoodsInfo.setCreateTime(DateUtils.getNowDate());
        tTerminalGoodsInfo.setId(IdUtils.simpleUUID());
        int i1 = tTerminalGoodsInfoMapper.insertTTerminalGoodsInfo(tTerminalGoodsInfo);
        if (StringUtils.isNotEmpty(tTerminalGoodsInfo.getSnCode())) {
            TTerminalInfo info = terminalInfoMapper.selectTTerminalInfoBySnCode(tTerminalGoodsInfo.getSnCode());
            if (StringUtils.isNull(info)) {
                throw new RuntimeException("未录入" + tTerminalGoodsInfo.getSnCode() + "SN端号");
            }
            if (YesOrNoEnums.NO.getCode().equals(info.getBindingStatus())) {
                throw new RuntimeException("终端号" + tTerminalGoodsInfo.getSnCode() + "已绑定，不能进行兑换");
            }
            tTerminalGoodsInfo.setBrandId(info.getBrandId());
        }
        if (StringUtils.isNotEmpty(tTerminalGoodsInfo.getGoodsImgS())) {
            String[] arr = tTerminalGoodsInfo.getGoodsImgS().split(",");
            for (int i = 0; i < arr.length; i++) {
                String img = arr[i];
                TTerminalGoodsImgInfo terminalGoodsImgInfo = new TTerminalGoodsImgInfo();
                terminalGoodsImgInfo.setId(IdUtils.simpleUUID());
                terminalGoodsImgInfo.setGoodsImg(img);
                terminalGoodsImgInfo.setGoodsId(tTerminalGoodsInfo.getId());
                terminalGoodsImgInfo.setSort(String.valueOf(i));
                terminalGoodsImgInfoMapper.insertTTerminalGoodsImgInfo(terminalGoodsImgInfo);
            }
        } else {
            throw new RuntimeException("最少录入一张商品轮播图片");
        }
        return i1;
    }

    /**
     * 修改商品基础
     *
     * @param tTerminalGoodsInfo 商品基础
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTTerminalGoodsInfo(TTerminalGoodsInfo tTerminalGoodsInfo) {
        terminalGoodsImgInfoMapper.deleteTTerminalGoodsImgInfoByGoodsId(tTerminalGoodsInfo.getId());
        if (StringUtils.isNotEmpty(tTerminalGoodsInfo.getGoodsImgS())) {
            String[] arr = tTerminalGoodsInfo.getGoodsImgS().split(",");
            for (int i = 0; i < arr.length; i++) {
                String img = arr[i];
                TTerminalGoodsImgInfo terminalGoodsImgInfo = new TTerminalGoodsImgInfo();
                terminalGoodsImgInfo.setId(IdUtils.simpleUUID());
                terminalGoodsImgInfo.setGoodsImg(img);
                terminalGoodsImgInfo.setGoodsId(tTerminalGoodsInfo.getId());
                terminalGoodsImgInfo.setSort(String.valueOf(i));
                terminalGoodsImgInfoMapper.insertTTerminalGoodsImgInfo(terminalGoodsImgInfo);
            }
        } else {
            throw new RuntimeException("最少录入一张商品轮播图片");
        }

        return tTerminalGoodsInfoMapper.updateTTerminalGoodsInfo(tTerminalGoodsInfo);
    }

    /**
     * 批量删除商品基础
     *
     * @param ids 需要删除的商品基础主键
     * @return 结果
     */
    @Override
    public int deleteTTerminalGoodsInfoByIds(String[] ids) {
        return tTerminalGoodsInfoMapper.deleteTTerminalGoodsInfoByIds(ids);
    }

    /**
     * 删除商品基础信息
     *
     * @param id 商品基础主键
     * @return 结果
     */
    @Override
    public int deleteTTerminalGoodsInfoById(String id) {
        return tTerminalGoodsInfoMapper.deleteTTerminalGoodsInfoById(id);
    }

    @Override
    public List<TTerminalGoodsInfo> queryTerminalAndExchange(TTerminalGoodsInfo tTerminalGoodsInfo) {
        List<TTerminalGoodsInfo> infos = tTerminalGoodsInfoMapper.queryTerminalAndExchange(tTerminalGoodsInfo);
        List<TTerminalBrandInfo> brandInfos = tTerminalBrandInfoMapper.selectTTerminalBrandInfoList(new TTerminalBrandInfo());
        infos.stream().forEach(bean -> {
            bean.setGoodsStatus(Optional.ofNullable(GoodsStatusEnum.getGoodsStatusEnum(bean.getGoodsStatus())).map(item -> item.getValue()).orElse(bean.getGoodsStatus()));
            brandInfos.stream().forEach(brand -> {
                if (StringUtils.isNotEmpty(bean.getBrandId()) && bean.getBrandId().equals(brand.getId())) {
                    bean.setBrandIdShow(brand.getBrand());
                }
            });
        });
        return infos;
    }

    //查询商品品牌
    @Override
    public List<TTerminalBrandInfo> queryBrand() {
        return tTerminalBrandInfoMapper.selectTTerminalBrandInfoList(new TTerminalBrandInfo());
    }

    //添加终端SN码
    @Override
    @Transactional
    public int insertList(TTerminalInfoWebDto dto) {
        //System.out.println(dto.getSnCode()+"==========");
        //System.out.println(1/0);
        List<TTerminalInfo> list = new ArrayList<>();
        TTerminalInfo term = new TTerminalInfo();
        term.setBrandId(dto.getBrandId());
        List<TTerminalInfo> tTerminalInfos = terminalInfoMapper.selectTTerminalInfoListForAdd(new TTerminalInfo());
/*        if (dto.getIsValid().equals("1")){//默认添加
            Long beginSnCode = Long.valueOf(dto.getBeginSnCode());//开始的sn码
            Long endSnCode = Long.valueOf(dto.getEndSnCode());//结束的sn码
            if (beginSnCode > endSnCode){
                throw  new RuntimeException("开始的SN码必须小于结束的SN码");
            }
            for (; beginSnCode <= endSnCode; beginSnCode++) {
                TTerminalInfo info = insertBean(dto);
                info.setSnCode(String.valueOf(beginSnCode));
                list.add(info);
            }
        }else {*/
        String[] snCodeArray = dto.getSnCode().split("\n");
        Set set = new HashSet<>(Arrays.asList(snCodeArray));
        if (set.size() != snCodeArray.length) {
            throw new IllegalArgumentException("重复的sn码");
        }
        for (String sn : dto.getSnCode().split("\n")) {
            TTerminalInfo info = insertBean(dto);
            info.setSnCode(sn.replaceAll(" ", ""));
            list.add(info);
            Optional.ofNullable(tTerminalInfos).ifPresent(map -> {
                map.stream().forEach(bean -> {
                    if (sn.equals(bean.getSnCode())) {
                        throw new RuntimeException(sn + "SN码重复");
                    }
                });
            });

        }
//        }
        return terminalInfoMapper.insertList(list);
    }

    public TTerminalInfo insertBean(TTerminalInfoWebDto dto) {
        TTerminalInfo info = new TTerminalInfo();
        info.setId(IdUtils.simpleUUID());
        info.setActivateStatus(YesOrNoEnums.YES.getCode());//是否出售（0：未出售，1：已出售）
        info.setSellStatus(YesOrNoEnums.YES.getCode());//是否激活（0：未激活，1：已激活）
        /*if (dto.getBindingTime() != null) {
            info.setBindingStatus(YesOrNoEnums.NO.getCode());//是否绑定用户（0：未绑定，1：已绑定）
        } else {
        }*/
        info.setBindingStatus(YesOrNoEnums.YES.getCode());//是否绑定用户（0：未绑定，1：已绑定），默认未绑定
        info.setCreateTime(DateUtils.getNowDate());//创建时间
        BeanUtils.copyProperties(dto, info);
        info.setTerminalGmv(null == dto.getTerminalGmv() ? BigDecimal.ZERO : dto.getTerminalGmv()); //初始化终端交易额
        info.setTerminalNum(null == dto.getTerminalGmv() ? BigDecimal.ZERO : BigDecimal.ONE); //初始化终端交易额
        return info;
    }

    //已实名认证的用户
    @Override
    public List<UserInfoVo> auditUserList() {
        TUserInfo userInfo = new TUserInfo();
        List<UserInfoVo> UserInfoVo = new ArrayList<>();
        userInfo.setAuditStatus(AuditStatusEnum.PASS_AUDIT.getCode());//实名审核通过
        userInfo.setAutonymType(YesOrNoEnums.YES.getCode());//已经实认证的状态
        List<TUserInfo> tUserInfos = tUserInfoMapper.selectTUserInfoList(userInfo);
        Optional.ofNullable(tUserInfos).ifPresent(map -> {
            map.stream().forEach(bean -> {
                UserInfoVo vo = new UserInfoVo();
                vo.setUserId(bean.getUserId());
                vo.setUserName(bean.getUserName());
                UserInfoVo.add(vo);
            });
        });
        return UserInfoVo;
    }
}
